import {getUserInfo, modifyUserBase} from '@/http/m_api/user'
import {defineStore} from 'pinia';
import appStore from './index';
import {ElMessage} from "element-plus";
import {avatar_path_pre} from "@/assets/ts/constant";

interface userInfo {
    email: string,
    username: string,
    birthday?: Date,
    createDate?: Date,
    avatarUrl?: any,
    name?: string,
    introduction?: string,
}

// 用户信息
export const useUserInfoStore = defineStore('userInfoStore', () => {
    const userInfo = ref<any>();
    const loginStatus = ref(false)

    function createUserInfo(userInfoObj: userInfo | null) {
        if (!userInfoObj) {
            clearUserInfo();
            return;
        }
        userInfo.value = {
            email: userInfoObj.email,
            user_name: userInfoObj.username,
            introduction: userInfoObj.introduction ? userInfoObj.introduction : "这个人很懒，什么都没有写。",
            createDate: userInfoObj.createDate ? new Date(userInfoObj.createDate) : new Date(),
            birthday: userInfoObj.birthday? new Date(userInfoObj.birthday) : null,
            name: userInfoObj.name ? userInfoObj.name : userInfoObj.username,
            avatar_url: userInfoObj.avatarUrl && userInfoObj.avatarUrl !== ''  ? `${avatar_path_pre}${userInfoObj.avatarUrl}` : require("@/assets/images/default.png"),
        }
        saveUserInfo()
    }

    function updateUserInfo(key: string, value: any) {
        userInfo.value[key] = value;
        saveUserInfo();
    }

    function saveUserInfo() {
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
    }

    function modifyUserInfo(){
        modifyUserBase({name: userInfo.value.name, birthday: userInfo.value.birthday})
    }

    function reloadUserInfo() {
        userInfo.value = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo') as string) : null;
        if (userInfo.value) {
            userInfo.value.createDate = new Date(userInfo.value.createDate);
            if (userInfo.value.birthday) {
                userInfo.value.birthday = new Date(userInfo.value.birthday);
            }
        }
    }

    function clearUserInfo() {
        userInfo.value = null;
        localStorage.removeItem('userInfo');
    }

    // 查询用户信息
    async function getAndUpdateUserInfo() {
        getUserInfo().then((data: any) => {
            createUserInfo(data.data)
            loginStatus.value = true;
        }).catch((e: any) => {
            keepLogout()
        })
    }

    function keepLogout() {
        userInfo.value = null
        loginStatus.value = false
    }

    // 查询用户当前用户简币信

    return {
        userInfo,
        loginStatus,
        modifyUserInfo,
        reloadUserInfo,
        createUserInfo,
        saveUserInfo,
        clearUserInfo,
        getAndUpdateUserInfo,
        updateUserInfo,
        keepLogout
    };
});
